package com.songcan.oauth.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.songcan.model.oauth.SysPosition;
import com.songcan.oauth.service.SysPositionService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;

@RestController
@RequestMapping("rest/position")
@AllArgsConstructor
public class PositionController {

    private final SysPositionService sysPositionService;


    @PostMapping()
    public void addPosition(@NotBlank(message = "名称不能为空")String name,
                            String description){
        sysPositionService.save(new SysPosition(IdWorker.getId(),name,description,new Date()));
    }

    @PutMapping()
    public void updatePosition(@NotNull(message = "id不能为空")Long id,
                               String name,String description){
        sysPositionService.saveOrUpdate(new SysPosition(id,name,description,new Date()));
    }


    @GetMapping("/list")
    public IPage<SysPosition> page(@RequestParam(defaultValue = "1")Integer page,
                                   @RequestParam(defaultValue = "20")Integer pageSize,
                                   String name){
        LambdaQueryWrapper<SysPosition> sysPositionLambdaQueryWrapper = Wrappers.lambdaQuery(new SysPosition());
        if(StrUtil.isNotEmpty(name)){
            sysPositionLambdaQueryWrapper.like(SysPosition::getName,"%"+name+"%");
        }
        sysPositionLambdaQueryWrapper.orderByDesc(SysPosition::getCreateTime);
        return  sysPositionService.page(new Page<>(page,pageSize));
    }

    @GetMapping()
    public SysPosition detail(@NotBlank(message = "id不能为空") Long id){
         return sysPositionService.getById(id);
    }


}
